package org.paul.gotobplan.manager;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.androidannotations.rest.spring.annotations.RestService;
import org.paul.gotobplan.base.BaseBean;
import org.paul.gotobplan.bean.LoginBean;
import org.paul.gotobplan.bean.SaveBean;
import org.paul.gotobplan.bean.TokenBean;
import org.paul.gotobplan.bean.UserBean;
import org.paul.gotobplan.rest.ISoftRestClient;
import org.paul.gotobplan.rest.RestClient;
import org.paul.gotobplan.rest.helper.MyErrorHandler;

import java.util.Map;

import static org.paul.gotobplan.BuildConfig.API_LV;


@EBean(scope = EBean.Scope.Singleton)
public class RestManager {

    private static final String TAG = "RestManager";

    @AfterInject
    void afterInject() {
        restClient.setRestErrorHandler(myErrorHandler);
    }

    @Bean
    MyErrorHandler myErrorHandler;

    @RestService
    RestClient restClient;
    @RestService
    ISoftRestClient iSoftRestClient;

    public LoginBean login(Map<String, Object> loginInfo) {

        LoginBean bean = restClient.login(API_LV, loginInfo);

        return handleResult(bean, LoginBean.class);
    }

    public void preToken() {
//        iSoftRestClient.preToken();
    }

    public TokenBean token() {
        return iSoftRestClient.token();
    }

    public UserBean user(String token, Map<String, Object> userInfo) {
        iSoftRestClient.setBearerAuth(token);
        return iSoftRestClient.user(userInfo);
    }

    public SaveBean am(String token, Map<String, Object> userInfo) {
        iSoftRestClient.setBearerAuth(token);
        return iSoftRestClient.am(userInfo);
    }

    public SaveBean pm(String token, Map<String, Object> userInfo) {
        iSoftRestClient.setBearerAuth(token);
        return iSoftRestClient.pm(userInfo);
    }

    private <T extends BaseBean> T handleResult(T bean, Class<T> clz) {
        if (null != bean) {
            return bean;
        } else {
            try {
                return clz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private void commonHeader() {
        iSoftRestClient.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.1.0; Redmi Note 5 Build/OPM1.171019.011; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.80 Mobile Safari/537.36;iPSAClient");
        iSoftRestClient.setHeader("Referer", "http://i.isoftstone.com/kaoqindakaweixinDTG/huawei.html?");
        iSoftRestClient.setHeader("Accept-Language", "zh-CN");
        iSoftRestClient.setHeader("Content-Type", "application/json");
        iSoftRestClient.setHeader("Origin", "http://i.isoftstone.com");
    }

}
